package com.example.shengyin.controller;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.entity.Admin;
import com.example.shengyin.entity.Comment;
import com.example.shengyin.entity.Page;
import com.example.shengyin.entity.User;
import com.example.shengyin.service.CommentService;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
@Validated
public class CommentController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CommentService service;

//    @PostMapping("/userInsert")
//    @ApiOperation("用户新增评论的方法，注意，如果没登录的时候，token为空，这个时候userid为空，前端展现评论的时候请把用户名改为游客")
//    public Result userInsert(@Valid @ApiParam(name = "articleid",value = "新闻号")@RequestParam Long articleid,
//                             @ApiParam(name = "content",value = "内容")@RequestParam String content, HttpServletRequest request) {
//        String ip = request.getRemoteAddr();
//        User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
//
//        Comment comment=new Comment();
//        comment.setArticleid(articleid);
//        comment.setContent(content);
//        System.out.println("==========-------=----------");
//        if (user==null) {
//            System.out.println("==========-------=----------");
//            comment.setUserid(0L);
//        } else {
//            comment.setUserid(user.getId());
//            long id = user.getId();
//            comment.setIp(ip);
//            comment.setUserid(id);
//        }
//        int r = service.userInsert(comment);
//        if (r > 0)
//            return Result.success("增加成功");
//        return Result.error("新增失败");
//    }

    @GetMapping("/comNum/{articleid}")
    @ApiOperation("传文章的id返回当前文章的所有评论")
    public Result comNum(@PathVariable(value = "articleid") Long articleid, HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }

        List<Comment> comments = service.comNum(articleid);

        return comments==null?Result.error("无评论"):Result.success(comments);
    }

    @GetMapping("/countByarticleid/{articleid}")
    @ApiOperation("传当前文章id返回文章的所有评论的数量")
    public Result countByarticleid(@PathVariable(value = "articleid") Long articleid,HttpServletRequest request){

        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }

        Long aLong = service.countByarticleid(articleid);
        return Result.success(aLong);
    }


    @ApiOperation("分页查询")
    @GetMapping("/list")
    public Result list(Page page,@ApiParam(name = "starttime",value = "开始时间") @RequestParam(required = false) Date starttime,@ApiParam(name = "endtime",value = "开始时间") @RequestParam(required = false) Date endtime,@RequestParam(required = false)String uname ,HttpServletRequest request)
    {

        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }

        List<Comment> list = service.list(page,starttime,endtime,uname);
        int count = service.count(starttime,endtime,uname);
        if(count==0||list==null)
            return Result.success(page,"没有数据");
        page.setData(list);
        page.setCount(count);
        System.out.println(JSON.toJSONString(Result.success(page)));
        return Result.success(page,"成功");
    }


    @ApiOperation("删除单个")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id")Long id, HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }

        int delete = service.delete(id);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }
    @ApiOperation("删除多个")
    @DeleteMapping("/deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable(value = "ids")String ids, HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }


        System.out.println("开始这些");
        String s = StrUtil.ListtoString(ids);
        int delete = service.deleteByIds(s);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @InitBinder// String----->Date
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
